import localforage from "localforage";

export default class CacheUtil {
    private cache: LocalForage | null = null
    private static instance: CacheUtil

    static getInstance(): CacheUtil {
        if (this.instance == null) {
            this.instance = new CacheUtil('cache', 'cache')
        }
        return this.instance
    }

    static newInstance(cacheName: string, storeName: string): CacheUtil {
        return new CacheUtil(cacheName, storeName)
    }

    private constructor(cacheName: string, storeName: string) {
        this.cache = localforage.createInstance({
            name: cacheName,
            storeName: storeName,
            driver: localforage.INDEXEDDB,
        })
    }

    put<T>(key: string, value: T): Promise<T> {
        return this.cache!.setItem(key, value)
    }

    get<T>(key: string): Promise<T | null> {
        return this.cache!.getItem(key)
    }

    remove(key: string): Promise<void> {
        return this.cache!.removeItem(key)
    }

    clear(): Promise<void> {
        return this.cache!.clear()
    }
}